<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>知识库管理</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
            background: #f2f2f2;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            background-attachment: fixed;
            background-image: url('./images/backgroud-ai.jpg');
            position: relative;
            height: 100vh;
            overflow: hidden;
        }

        body::before {
            content: "";
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.4);
            z-index: -1;
        }

        .header-title {
            color: white;
            text-align: center;
            margin-bottom: 20px;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
            font-size: 28px;
        }

        #container {
            width: 1200px;
            height: calc(100vh - 100px);
            background: rgba(255, 255, 255, 0.95);
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            margin: 0 auto;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .main-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }

        /* 文件上传区域样式 */
        #upload-area {
            width: 100%;
            margin-bottom: 20px;
            border: 2px dashed #ccc;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            background-color: #f9f9f9;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        #upload-area:hover {
            border-color: #007bff;
            background-color: #e9f4ff;
        }

        #upload-area.dragover {
            border-color: #007bff;
            background-color: #ddefff;
        }

        #upload-area h3 {
            color: #333;
            margin-bottom: 10px;
        }

        #upload-area p {
            color: #666;
            font-size: 14px;
        }

        #file-input {
            display: none;
        }

        #upload-btn {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 15px;
        }

        #upload-btn:hover {
            background-color: #0056b3;
        }

        #upload-btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        /* 上传结果样式 */
        #upload-result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 5px;
            display: none;
        }

        .result-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .result-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* 文件列表样式 */
        #file-list {
            margin-top: 30px;
        }

        #file-list h3 {
            margin-bottom: 15px;
            color: #333;
        }

        #files-container {
            max-height: 300px;
            overflow-y: auto;
        }

        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin-bottom: 10px;
            background-color: #fff;
        }

        .file-info {
            flex: 1;
        }

        .file-name {
            font-weight: bold;
            color: #333;
        }

        .file-meta {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }

        .delete-btn {
            background-color: #dc3545;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 14px;
        }

        .delete-btn:hover {
            background-color: #c82333;
        }

        .delete-btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        /* 返回按钮 */
        #back-btn {
            position: absolute;
            top: 30px;
            left: 30px;
            background-color: #6c757d;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }

        #back-btn:hover {
            background-color: #5a6268;
        }

        /* 响应式设计 */
        @media (max-width: 1200px) {
            #container {
                width: 95%;
            }
        }

        @media (max-width: 768px) {
            body {
                padding: 10px;
            }

            #container {
                height: calc(100vh - 20px);
            }

            .header-title {
                font-size: 24px;
            }
        }
    </style>
</head>
<body>
    <button id="back-btn" onclick="goBack()">← 返回主界面</button>
    <h1 class="header-title">知识库管理</h1>
    
    <div id="container">
        <div class="main-content">
            <!-- 文件上传区域 -->
            <div id="upload-area" onclick="document.getElementById('file-input').click()">
                <h3>上传文件到知识库</h3>
                <p>支持 PDF、TXT、MD、DOCX 文件格式</p>
                <p>拖拽文件到此区域或点击选择文件</p>
                <button id="upload-btn">选择文件</button>
                <input type="file" id="file-input" multiple accept=".pdf,.txt,.md,.docx,.markdown">
            </div>
            
            <!-- 上传结果提示 -->
            <div id="upload-result"></div>
            
            <!-- 文件列表区域 -->
            <div id="file-list">
                <h3>已上传文件</h3>
                <div id="files-container">
                    <!-- 文件列表将通过JavaScript动态生成 -->
                </div>
            </div>
        </div>
    </div>

    <script>
        // 页面加载完成后初始化
        window.addEventListener('load', function() {
            loadFileList();
            setupDragAndDrop();
        });

        // 设置拖拽上传功能
        function setupDragAndDrop() {
            const uploadArea = document.getElementById('upload-area');
            const fileInput = document.getElementById('file-input');
            
            // 阻止默认拖拽行为
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                uploadArea.addEventListener(eventName, preventDefaults, false);
            });
            
            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }
            
            // 高亮拖拽区域
            ['dragenter', 'dragover'].forEach(eventName => {
                uploadArea.addEventListener(eventName, highlight, false);
            });
            
            ['dragleave', 'drop'].forEach(eventName => {
                uploadArea.addEventListener(eventName, unhighlight, false);
            });
            
            function highlight() {
                uploadArea.classList.add('dragover');
            }
            
            function unhighlight() {
                uploadArea.classList.remove('dragover');
            }
            
            // 处理文件拖拽放下
            uploadArea.addEventListener('drop', handleDrop, false);
            
            function handleDrop(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                handleFiles(files);
            }
            
            // 处理文件选择
            fileInput.addEventListener('change', function() {
                handleFiles(this.files);
                this.value = ''; // 重置input值，以便可以重复选择相同文件
            });
        }

        // 处理文件上传
        async function handleFiles(files) {
            if (files.length === 0) return;
            
            const uploadBtn = document.getElementById('upload-btn');
            const resultDiv = document.getElementById('upload-result');
            
            // 禁用上传按钮
            uploadBtn.disabled = true;
            uploadBtn.textContent = '上传中...';
            
            try {
                // 逐个上传文件
                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    await uploadFile(file);
                }
                
                // 显示成功消息
                showResult('文件上传成功！', 'success');
                
                // 重新加载文件列表
                await loadFileList();
            } catch (error) {
                console.error('上传失败:', error);
                showResult(`上传失败: ${error.message}`, 'error');
            } finally {
                // 恢复上传按钮
                uploadBtn.disabled = false;
                uploadBtn.textContent = '选择文件';
            }
        }

        // 上传单个文件
        async function uploadFile(file) {
            const formData = new FormData();
            formData.append('file', file);
            
            const response = await fetch('http://localhost:3000/upload', {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.details || errorData.error || '上传失败');
            }
            
            return await response.json();
        }

        // 显示上传结果
        function showResult(message, type) {
            const resultDiv = document.getElementById('upload-result');
            resultDiv.textContent = message;
            resultDiv.className = type === 'success' ? 'result-success' : 'result-error';
            resultDiv.style.display = 'block';
            
            // 3秒后自动隐藏结果
            setTimeout(() => {
                resultDiv.style.display = 'none';
            }, 3000);
        }

        // 加载文件列表
        async function loadFileList() {
            try {
                // 获取向量数据来提取文件信息
                // 注意：这需要后端提供一个专门的API来获取文件列表
                const response = await fetch('http://localhost:3000/vector-files');
                
                if (response.ok) {
                    const files = await response.json();
                    renderFileList(files);
                } else {
                    // 如果API不存在，显示提示信息
                    renderFileList([]);
                }
            } catch (error) {
                console.error('加载文件列表失败:', error);
                renderFileList([]);
            }
        }

        // 渲染文件列表
        function renderFileList(files) {
            const container = document.getElementById('files-container');
            
            if (files.length === 0) {
                container.innerHTML = '<p>暂无文件，请先上传文件到知识库。</p>';
                return;
            }
            
            // 按文件名分组
            const fileGroups = {};
            files.forEach(file => {
                if (!fileGroups[file.filename]) {
                    fileGroups[file.filename] = [];
                }
                fileGroups[file.filename].push(file);
            });
            
            // 生成文件列表HTML
            let html = '';
            for (const filename in fileGroups) {
                const fileItems = fileGroups[filename];
                const chunksCount = fileItems.length;
                
                html += `
                    <div class="file-item">
                        <div class="file-info">
                            <div class="file-name">${filename}</div>
                            <div class="file-meta">包含 ${chunksCount} 个文本块</div>
                        </div>
                        <button class="delete-btn" onclick="deleteFile('${filename}')">删除</button>
                    </div>
                `;
            }
            
            container.innerHTML = html;
        }

        // 删除文件
        async function deleteFile(filename) {
            if (!confirm(`确定要删除文件 "${filename}" 吗？这将从知识库中移除该文件的所有内容。`)) {
                return;
            }
            
            try {
                // 注意：这需要后端提供一个专门的API来删除文件
                const response = await fetch(`http://localhost:3000/vector-files/${encodeURIComponent(filename)}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    showResult(`文件 "${filename}" 删除成功！`, 'success');
                    await loadFileList(); // 重新加载文件列表
                } else {
                    const errorData = await response.json();
                    throw new Error(errorData.error || '删除失败');
                }
            } catch (error) {
                console.error('删除失败:', error);
                showResult(`删除失败: ${error.message}`, 'error');
            }
        }

        // 返回主界面
        function goBack() {
            window.location.href = './index.html';
        }
    </script>
</body>
</html>